<template>
  <dv-border-box-10
    :style="{ '--right': right + 'px' }"
    backgroundColor="#00003bc1"
    :color="['#4789e3', '#65bfe5']"
    class="right-row-bg"
  >
    <div class="right-row-box">
      <div class="content">
        <div class="tools">
          <dv-decoration-7 :dur="2" class="title"
            >&nbsp;<font size="5">查询</font>&nbsp;</dv-decoration-7
          >
          <div class="tool">
            <i class="el-icon-close" @click="removeFn"></i>
          </div>
        </div>
        <!-- <div class="box-content">
          <h3 class="title">关键词查询</h3>
          <div class="card">
            <div class="card-item">
              <el-input placeholder="请输入关键词" v-model="keyword">
                <el-button slot="append" icon="el-icon-search" @click="byKeyWordsQueryFn"></el-button>
              </el-input>
              <p><b>*</b> 根据地名关键词搜索，如“新疆喀什地区”等</p>
            </div>
          </div>
          <h3 class="title">时间段查询</h3>
          <div class="card">
            <div class="card-item">
              <el-date-picker
                v-model="timeBucket"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
              <el-button slot="append" icon="el-icon-search"></el-button>
              <p><b>*</b> 根据地震发生时间查询，如“2009-01-01到2012-11-30”等</p>
            </div>
          </div>
          <h3 class="title">几何体查询</h3>
          <div class="card">
            <div class="card-item">
              <el-select v-model="feature" clearable placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.title"
                  :label="item.title"
                  :value="item.layer"
                >
                </el-option>
              </el-select>
              <el-button slot="append" icon="el-icon-search"></el-button>
              <p>
                <b>*</b>
                根据面状几何体查询，几何体可以在“工具菜单栏”“创建要素”创建使用。
              </p>
            </div>
          </div>
        </div> -->
        <div class="box-content">
          <el-collapse v-model="activeNames" @change="handleChange">
            <el-collapse-item name="1">
              <template slot="title">
                <h3 class="title">关键词查询</h3>
              </template>
              <div class="card">
                <div class="card-item">
                  <el-input placeholder="请输入关键词" v-model="keyword">
                    <el-button
                      slot="append"
                      icon="el-icon-search"
                      @click="byKeyWordsQueryFn"
                    ></el-button>
                  </el-input>
                  <p><b>*</b> 根据地名关键词搜索，如“新疆喀什地区”等</p>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item name="2">
              <template slot="title">
                <h3 class="title">时间段查询</h3>
              </template>
              <div class="card">
                <div class="card-item">
                  <el-date-picker
                    v-model="timeBucket"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                  >
                  </el-date-picker>
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="byTimeQueryFn"
                  ></el-button>
                  <p>
                    <b>*</b> 根据地震发生时间查询，如“2009-01-01到2012-11-30”等
                  </p>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item name="3">
              <template slot="title">
                <h3 class="title">几何体查询</h3>
              </template>

              <div class="card">
                <div class="card-item">
                  <el-select
                    v-model="uid"
                    clearable
                    placeholder="请选择"
                    @change="$forceUpdate()"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.uid"
                      :label="item.title"
                      :value="item.uid"
                      :disabled="
                        item.type != 'Polygon' && item.type != 'Circle'
                      "
                    >
                    </el-option>
                  </el-select>
                  <el-button
                    slot="append"
                    icon="el-icon-search"
                    @click="byGeometryQueryFn"
                  ></el-button>
                  <p>
                    <b>*</b>
                    根据面状几何体查询，几何体可以在“工具菜单栏”“创建要素”创建使用。
                  </p>
                </div>
              </div>
            </el-collapse-item>
            <el-divider></el-divider>
            <el-collapse-item name="4">
              <template slot="title">
                <h3 class="title">结果数据集</h3>
              </template>
              <div v-if="resultes.length > 0" class="card">
                <el-collapse class="result" accordion>
                  <el-collapse-item
                    v-for="(item, index) in resultes"
                    :key="item.id"
                  >
                    <template slot="title">
                      &nbsp;&nbsp;
                      <!-- <el-checkbox
                        v-model="item.load"
                        title="加载到地图"
                      ></el-checkbox> -->
                      <p class="idx">{{ index + 1 }}</p>
                      <div class="card-item results">
                        <div class="">
                          <p style="">{{ item.title }}</p>

                          <span>数据量：{{ item.length }} 条</span>&nbsp;&nbsp;
                          <span
                            >状态：
                            <template v-if="item.load"> 已加载 </template>
                            <template v-else> 未加载 </template> </span
                          >&nbsp;&nbsp;
                          <!-- <span>
                            <i class="el-icon-delete-solid" title="删除"></i>
                          </span> -->
                        </div>
                      </div>
                      <el-dropdown trigger="hover">
                        <span class="el-dropdown-link">
                          <i class="el-icon-more el-icon--left icon-menu"></i>
                        </span>
                        <el-dropdown-menu
                          slot="dropdown"
                          class="re-el-dropdown-menu"
                        >
                          <el-dropdown-item
                            icon="el-icon-connection"
                            @click.native="loadToMap(item)"
                            >加载到地图</el-dropdown-item
                          >
                          <el-dropdown-item
                            icon="el-icon-download"
                            @click.native="downloadFile(item)"
                            >下载</el-dropdown-item
                          >
                          <el-dropdown-item
                            icon="el-icon-delete"
                            @click.native="deleteItem(item)"
                            >删除</el-dropdown-item
                          >
                        </el-dropdown-menu>
                      </el-dropdown>
                    </template>
                    <template>
                      <div
                        class="item"
                        v-for="(i, index) in item.points.slice(0, 100)"
                        :key="index"
                      >
                        <p class="idx">{{ index + 1 }}</p>
                        <div class="left">
                          <p class="location">地点：{{ i.location }}</p>
                          <p>
                            <span>E:{{ i.lon }}</span
                            >&nbsp; <span>N:{{ i.lat }}</span
                            >&nbsp; <span>震级: {{ i.scale }}</span
                            >&nbsp;
                            <span>深度: {{ i.depth }}km</span>
                          </p>
                        </div>
                        <div class="right">
                          <i
                            class="el-icon-map-location"
                            title="定位到地图上"
                            @click="location(i, item)"
                          ></i>
                        </div>
                      </div>
                      <div class="warning" v-if="item.length > 100">
                        <p>
                          目前只显示前 100 个，剩下的请<br />下载后查看！！！
                        </p>
                      </div>
                    </template>
                  </el-collapse-item>
                </el-collapse>
              </div>
              <template v-else>
                <p style="color: red; text-align: center">
                  暂无用户查询数据集...
                </p>
              </template>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>
  </dv-border-box-10>
</template>

<script>
import {
  getCityNameQuery,
  byTimeBucketQuery,
  byGeometryQuery,
  excelExport,
} from "@/api";
import { toLonLat, fromLonLat } from "@/utils";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Feature } from "ol";
import { Point } from "ol/geom";
import { Style, Stroke, Fill, Circle as CircleStyle } from "ol/style";
import ColorUtils from "@/utils/colorUtils";
export default {
  name: "Test1LeftRow",
  data() {
    return {
      right: -500,
      flag: "M3",
      keyword: "",
      timeBucket: "",
      options: this.$store.getters.getLayeres.ul,
      uid: "",
      activeNames: ["4"],
      resultes: [{}, {}],
      checked: "",
      featuresArr: [],
    };
  },

  mounted() {},
  props: {
    Map: {
      type: Object,
      requered: true,
    },
  },
  computed: {
    getMenuFlag() {
      return this.$store.state.activeMenu;
    },
    getSelection() {
      return this.$store.state.selections;
    },
  },
  watch: {
    getMenuFlag: {
      handler(newValue, oldValue) {
        // console.log(newValue, oldValue);
        this.right = -500;
        if (newValue === this.flag) {
          this.right = 0;
        }
      },
      deep: true,
      immediate: true,
    },
    getSelection: {
      handler(newValue, oldValue) {
        this.resultes = newValue;
      },
      deep: true,
      immediate: true,
    },
  },

  methods: {
    removeFn() {
      console.log("removeFn");
      this.right = -500;
    },
    async byKeyWordsQueryFn() {
      if (this.keyword == "") return this.$message.error("请输入关键字");
      const { data: res } = await getCityNameQuery(this.keyword);
      if (res) {
        let l = {
          id: new Date().getTime(),
          title: "关键词  '" + this.keyword + "'  查询",
          length: res.length,
          load: false,
          points: res,
        };

        // 数据集中提交
        let selections = this.$store.state.selections;
        selections.push(l);
        this.$store.commit("setSelections", selections);
      }
      // console.log(res);
    },
    handleChange(val) {
      // console.log(val);
    },
    async byTimeQueryFn() {
      if (this.timeBucket == "")
        return this.$message.error("请选择时间范围!!!");

      let start = this.timeBucket[0];
      let end = this.timeBucket[1];

      const { data: res } = await byTimeBucketQuery(start, end);

      if (res) {
        let l = {
          id: new Date().getTime(),
          title: "时间段  '" + start + " 到 " + end + "'  查询",
          length: res.length,
          load: false,
          points: res,
        };

        // 数据集中提交
        let selections = this.$store.state.selections;
        selections.push(l);
        this.$store.commit("setSelections", selections);
      }
    },
    async byGeometryQueryFn() {
      const geom = this.options.filter((item) => item.uid === this.uid)[0]
        .layer;
      var s = geom
        .getSource()
        .getFeatures()[0]
        .getGeometry()
        .getFlatCoordinates();
      const result = [];
      for (let i = 0; i < s.length; i += 2) {
        result.push(toLonLat(s[i], s[i + 1]));
      }
      let type = geom.get("type").toLocaleUpperCase();
      const { data: res } = await byGeometryQuery(type, result, "4326");
      if (res) {
        let l = {
          id: new Date().getTime(),
          title: "几何体  '" + geom.get("title") + "'  查询",
          length: res.length,
          load: false,
          points: res,
        };

        // 数据集中提交
        let selections = this.$store.state.selections;
        selections.push(l);
        this.$store.commit("setSelections", selections);
      }
    },
    loadToMap(i) {
      if (i.length <= 0) return this.$message.warning("没有数据");

      if (i.load) return this.$message.warning("数据已加载到地图");

      if (i.length >= 1000) {
        this.$message.info("所加载的数据量较大，请耐心等待！！！");
      }

      const newStyle = {
        symbol: {
          symbolType: "circle", //图标形状可选值为：circle/triangle/square/image

          size: [
            //大小

            "interpolate",

            ["linear"],

            ["get", "population"],

            40000,

            8,

            2000000,

            28,
          ],

          color: ["match", ["get", "hover"], 1, "#ff3f3f", "#006688"], //设置hover值为1时的颜色为：#ff3f3f,默认颜色为：#006688

          rotateWithView: false, //是否随视图旋转

          offset: [0, 0], //偏移

          opacity: [
            //透明度

            "interpolate",

            ["linear"],

            ["get", "population"],

            40000,

            0.6,

            2000000,

            0.92,
          ],
        },
      };
      let style = {
        symbol: {
          symbolType: "image",
          size: 3,
          color: "red",
        },
      };

      let _this = this;

      // 循环添加feature
      let m = i.length > 500 ? 500 : i.length;
      for (let k = 0; k < m; k++) {
        let coordinate = fromLonLat(i.points[k].lon, i.points[k].lat);
        // console.log(i);
        let feature = new Feature({
          geometry: new Point(coordinate),
          scale: i.points[k].scale,
          d_id: i.points[k].id,
        });
        this.featuresArr.push(feature);
      }
      this.Map.on("click", (evt) => {
        this.clickMap(evt);
      });

      let vectorSource = new VectorSource({
        features: this.featuresArr,
        //   url: "http://localhost:8080/geoJson/data.geojson",
        //   format: new GeoJSON(),
        wrapX: false,
      });

      // let pointLayer = new WebGLPointsLayer({
      //   source: vectorSource,
      //   style: style,
      //   zIndex: 999,
      //   title: i.title,
      //   name: "",
      //   type: "PointCollection",
      //   wrapX: false,
      // });
      var color = ColorUtils.getColor();
      let pointLayer = new VectorLayer({
        source: vectorSource,
        isRemove: false,
        style: function (feature) {
          let c = feature.get("scale");
          return new Style({
            image: new CircleStyle({
              radius: c * 2,
              fill: new Fill({
                color: color,
              }),
              stroke: new Stroke({
                width: 1,
                color: "black",
              }),
            }),
          });
        },
        zIndex: 999,
        title: i.title,
        name: "",
        type: "PointCollection",
        wrapX: false,
      });
      this.Map.addLayer(pointLayer);

      let l = {
        title: pointLayer.get("title"),
        name: pointLayer.get("name"),
        uid: pointLayer.ol_uid,
        id: i.id,
        visible: pointLayer.get("visible"),
        type: pointLayer.get("type"),
        edit: false,
        delete: true,
        layer: pointLayer,
        children: []
      };
      let layeres = this.$store.getters.getLayeres;
      layeres.ul.push(l);
      this.$store.commit("setLayeres", layeres);

      i.load = true;
      this.featuresArr = [];
    },
    async downloadFile(i) {
      let d = {
        points: i.points,
        title: i.title,
      };
      const res = await excelExport(d);
      if (res.data === null) return this.$message.warning("导出失败");

      // post 请求中浏览器不会出发自动下载，所以在浏览器上创建下载链接再触发下载事件
      let blob = new Blob([res.data], {
        // type: "application/vnd.ms-excel;charset=utf-8",    // 适合于 xls 文件
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", //适合于 xlsx 文件
      }); // 文件类型
      let url = window.URL.createObjectURL(blob); // 创建下载链接
      window.open(url);
      this.$message.success("导出成功");
    },
    deleteItem(i) {
      this.resultes = this.resultes.filter((item) => item !== i);

      // 数据集中提交
      let selections = this.$store.state.selections;
      selections = this.resultes;
      this.$store.commit("setSelections", selections);
    },
    location(point, item) {
      if(item.load === false){
        return this.$notify.warning({title: '提示',message: '请先数据加载到地图中'})
      }
      var center = fromLonLat(point.lon, point.lat);
      this.Map.getView().animate({
        // 只设置需要的属性即可
        center: center, // 中心点
        zoom: 9, // 缩放级别
        rotation: undefined, // 缩放完成view视图旋转弧度
        duration: 1000, // 缩放持续时间，默认不需要设置
      });
    },
    clickMap(evt) {
      let featureMouseOver = this.Map.forEachFeatureAtPixel(
        evt.pixel,
        function (feature, layer) {
          return feature;
        }
      );
      if (!featureMouseOver) return;
      if (!featureMouseOver.get("d_id")) return;
      this.$store.commit("setActiveMenu", "M0");
      this.$store.commit("setSelectedId", featureMouseOver.get("d_id"));
    },
  },
};
</script>

<style lang="less" scoped>
.right-row-bg {
  position: absolute;
  top: 0;
  right: var(--right);
  bottom: 0;
  width: 20%;
  margin: 5px;
  z-index: 9;
  backdrop-filter: saturate(150%) blur(8px);
  -webkit-backdrop-filter: saturate(150%) blur(8px);
  animation: run 1s linear;
  color: #1dc1f5;
}

@keyframes run {
  0% {
    left: -100%;
  }

  100% {
    left: 0;
  }
}

.right-row-box {
  position: absolute;

  top: 0;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  // color: #4789e3;
  // color: #3f96a5;

  .border-box {
    width: 95%;
    height: 150px;
  }

  // .tolbar {
  //     width: 100%;
  //     height: 5%;
  // }

  .content {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: flex-start;
    width: 100%;
    height: 100%;
  }
  .box-content {
    .title {
      text-align: left;
      margin: 10px;
      padding-left: 5px;
      border-left: 5px #139fc0 solid;
      font-size: 18px;
      font-family: "Courier New", Courier, monospace;
    }
    .card {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: flex-start;

      .card-item {
        width: 100%;
        padding: 10px 15px;
        border-radius: 8px;
        background-color: #2f338a;
        transition: 0.3s linear;

        p {
          font-size: 16px;
          font-weight: bold;
          text-align: start;
        }
      }
      .results {
        width: 100%;
        padding: 10px 10px;

        p {
          margin-top: 0px;
        }
      }
      .item {
        display: flex;
        flex-direction: row;
        height: 50px;
        justify-content: space-between;
        padding: 5px 10px;
        border-bottom: 1px dashed;
        .left {
          width: 80%;
          display: flex;
          flex-wrap: wrap;
          flex-direction: row;
          p {
            margin: 0;
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
            width: 100%;
            display: inline-block;
          }
          .location {
            font-weight: bold;
            font-size: 16px;
          }
        }
        .right {
          width: 20%;
          display: flex;
          align-items: center;
          flex-wrap: nowrap;
          justify-content: space-evenly;

          i {
            font-size: 24px;
            transition: all 0.1s linear;
            cursor: pointer;
            &:hover {
              scale: 1.01;
            }
          }
        }

        .idx {
          text-align: center;
          margin-right: 15px;
          font-weight: bold;
        }
      }
    }
  }
  .box-content:nth-child(1n) {
    flex: 2;
  }

  .box-content:nth-child(2n) {
    flex: 1;
  }
}

.tools {
  // display: flex;
  // flex-direction: row;
  // flex-wrap: nowrap;
  // justify-content: space-around;
  // align-items: center;
  position: relative;
  width: 100%;
  margin-bottom: 5px;

  .title {
    width: 100%;
    height: 30px;
  }

  .tool {
    position: absolute;
    right: 10px;
    top: 5px;
    background: #4687e240;
  }
}

.el-descriptions {
  background-color: transparent !important;
  color: #1dc1f5 !important;
  font-size: 18px;
}

.margin-left {
  margin-left: 10px;
}
.el-date-editor--daterange.el-input,
.el-date-editor--daterange.el-input__inner,
.el-date-editor--timerange.el-input,
.el-date-editor--timerange.el-input__inner {
  width: 79% !important;
}
</style>
<style>
.el-collapse {
  border: none;
}
.el-collapse-item__header,
.el-collapse-item__wrap,
.el-collapse-item__content {
  background-color: transparent;
  color: var(--t-color);
  text-align: start;
}

.el-collapse-item__header {
  line-height: normal;
  border: none;
}
.el-collapse-item__content {
  padding-bottom: 0%;
}
.el-collapse-item__wrap {
  border-bottom: none;
  /* border-bottom: 1px dashed var(--t-color); */
}
.result {
  width: 100%;
  height: 100%;
}
.result .el-collapse-item__header,
.result.el-collapse-item__wrap,
.result.el-collapse-item__content {
  background-color: #2f338a;
}
.result .el-collapse-item__header {
  height: 100%;
  margin: 0px 8px;
  border-radius: 4px;
  border-bottom: 1px dashed;
}
.result .el-collapse-item__wrap {
  max-height: 250px;
  margin: 0px 8px;
  background-color: #2f348aa0;
  overflow-y: auto;
}

::-webkit-scrollbar {
  /* 修改滚动条的宽度 */
  width: 4px;
  height: 2px;
  /* display: none; */
}

::-webkit-scrollbar-track {
  /* 修改滚动条的轨道颜色 */
  background-color: #007bffa3;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb {
  /* 修改滚动条滑块的颜色 */
  background-color: #007bff;
  border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
  /* 修改滚动条滑块在悬停状态下的颜色 */
  background-color: #0056b3;
}

.warning {
  width: 100%;
  color: #e6a23c;
  text-align: center;
}

.icon-menu {
  transform: rotate(90deg) !important;
}
.icon-menu::before {
  font-size: 20px !important;
  color: var(--t-color) !important;
}
.re-el-dropdown-menu {
  background-color: var(--b-color-1);
  border: none;
  color: var(--t-color) !important;
}

/* 消除小三角 */
.el-popper[x-placement^="bottom"] .popper__arrow {
  border: none;
}
.el-popper[x-placement^="bottom"] .popper__arrow::after {
  border: none;
}

.el-dropdown-menu__item {
  color: var(--t-color) !important;
}
</style>
